package com.hongminzheng.openapi.controller;

import com.github.pagehelper.PageInfo;
import com.hongminzheng.openapi.bean.Result;
import com.hongminzheng.openapi.bean.TableData;
import com.hongminzheng.openapi.pojo.Application;
import com.hongminzheng.openapi.service.ApplicationService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author hmz
 * @version v1.0
 * @data 2020/09/29
 **/
@RestController
@RequestMapping("/application")
public class ApplicationController {
    /**
     * 创建服务层对象
     */
    @Autowired
    private ApplicationService applicationService;

    @PostMapping("/add")
    public Result insertApplication(Application application){
        try {
            applicationService.insert(application);
            return new Result(true, "添加成功");
        } catch (Exception e) {
            return new Result(false, "添加失败");
        }
    }

    /**
     * 更新
     * @param application
     * @return
     */
    @RequestMapping("/update")
    public Result updateApplication(Application application){
        try {
            applicationService.updateByPrimaryKey(application);
            return new Result(true, "更新成功");
        } catch (Exception e) {
            return new Result(false, "更新失败");
        }
    }


    /**
     * 删除
     * @param
     * @return
     */
    @PostMapping("/dels")
    public Result dels(@RequestBody List<Application> applicationList) {
        //创建返回对象
        Result result = new Result();
        //创建循环，调用删除方法
        applicationList.forEach(application -> {
            applicationService.deleteByPrimaryKey(application.getId());
        });
        result.setStatus(true);
        result.setMessage("批量删除成功");
        return result;
    }

    @GetMapping("/page")
    public TableData<Application> findLayuiPage(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit,String cropName){
        Application application = new Application();
        application.setCropName(cropName);

        TableData<Application> applicationTableData = new TableData<>();
        PageInfo<Application> pageInfo = applicationService.findPage(page, limit, application);

        applicationTableData.setCount(pageInfo.getTotal());
        applicationTableData.setData(pageInfo.getList());
        return applicationTableData;
    }


}
